package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;


// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    @Autowired
    AddressMapper addressMapper;

    @Override
    public List<Address> list() {

        //select * from address_book where user_id = ?;
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());
        return addressMapper.selectList(qw);
    }

    @Override
    public void add(Address address) {
        //补充id
        address.setUserId(UserHolder.get().getId());
        //补充是否为默认地址
        address.setIsDefault(0);
        //添加进数据库
        addressMapper.insert(address);
    }

    @Override
    public void update(Address newAddress) {
        //先把所有地址都设为非默认
        Address oldAddress = new Address();
        oldAddress.setIsDefault(0);

        //update address_book set is_default=0 where user_id =?
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());


        addressMapper.update(oldAddress,qw);

        newAddress.setIsDefault(1);
        addressMapper.updateById(newAddress);

    }

    @Override
    public Address findDefault() {
        //select * from address_book where is_default = ? and user_id = ?;
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        qw.eq(Address::getIsDefault,1);

        return addressMapper.selectOne(qw);
    }

    @Override
    public Address findById(Long id) {
        //select * from address_book where user_id = ? and id = ?;
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        qw.eq(Address::getId,id);
        Address address = addressMapper.selectOne(qw);
        return address;
    }

    @Override
    public void updateAddress(Address address) {
        addressMapper.updateById(address);
    }
}
